package com.centaline.androidsalesblog.activities.mine;

import android.content.Intent;
import android.text.TextUtils;

import com.android.volley.VolleyError;
import com.centaline.androidsalesblog.R;
import com.centaline.androidsalesblog.activities.newest.NewEstActDetailActivity;
import com.centaline.androidsalesblog.adapter.NewEstActAdapter;
import com.centaline.androidsalesblog.api.newest.NewEstActListApi;
import com.centaline.androidsalesblog.api.usercenter.UserBookingListApi;
import com.centaline.androidsalesblog.base.BaseActivity;
import com.centaline.androidsalesblog.constants.AppConstant;
import com.centaline.androidsalesblog.constants.CommonConstant;
import com.centaline.androidsalesblog.constants.ExtraConstant;
import com.centaline.androidsalesblog.model.businissobject.UserBookBo;
import com.centaline.androidsalesblog.model.databaseobject.BizUnitDo;
import com.centaline.androidsalesblog.model.databaseobject.NewEstActDo;
import com.centaline.androidsalesblog.model.databaseobject.UserDo;
import com.centaline.androidsalesblog.model.responseobject.NewEstActListRo;
import com.centaline.androidsalesblog.model.responseobject.UserBookListRo;
import com.centaline.androidsalesblog.rx.database.RxDataBase;
import com.centaline.androidsalesblog.widgets.MRecyclerView;
import com.centanet.framework.glide.GlideLoad;
import com.centanet.framework.interfaces.IRecycleViewListener;
import com.centanet.framework.interfaces.IResponseListener;
import com.trello.rxlifecycle.ActivityEvent;

import java.util.ArrayList;

import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;

/**
 * 我的活动
 * <p/>
 * Created by fusl1 on 2015/12/23.
 * Modify by Lihq on 2016/01/20
 */
public class MyActivityActivity extends BaseActivity {

    private MRecyclerView mRecyclerView;

    private ArrayList<UserBookBo> userBookBoList = new ArrayList<>();
    private ArrayList<NewEstActDo> userActList = new ArrayList<>();
    private NewEstActAdapter newEstActAdapter;
    private UserBookingListApi userBookingListApi;
    private NewEstActListApi newEstActListApi;

    private int iRefreshType;
    private String userPhone;

    @Override
    protected int setLayoutId() {
        return R.layout.activity_new_est_act_list;
    }

    @Override
    protected void findViews() {
        setUniversalToolbar(R.string.title_my_activity);
        mRecyclerView = (MRecyclerView) findViewById(R.id.mRecyclerView);
    }

    @Override
    protected void initViews() {
        newEstActAdapter = new NewEstActAdapter(this, GlideLoad.init(this), userActList);
        mRecyclerView.setAdapter(newEstActAdapter);
        mRecyclerView.setIRecycleViewListener(new IRecycleViewListener() {
            @Override
            public void downRefresh() {
                iRefreshType = 1;
                userBookingListApi.setFirstIndex(0);
                requestUserBookingList();
            }

            @Override
            public void upRefresh() {
                iRefreshType = 2;
                userBookingListApi.setFirstIndex(userBookBoList.size());
                requestUserBookingList();
            }

            @Override
            public void onItemClick(int position) {
                startActivity(new Intent(MyActivityActivity.this, NewEstActDetailActivity.class)
                        .putExtra(ExtraConstant.NewEstActId, userActList.get(position).getActId()));
            }
        });
        userBookingListApi = new UserBookingListApi(MyActivityActivity.class, UserBookListRo.class, new IResponseListener<UserBookListRo>() {
            @Override
            public void onResponse(UserBookListRo userBookListRo) {
                final ArrayList<UserBookBo> temp = userBookListRo.getList();
                if (iRefreshType == 1) {
                    userBookBoList.clear();
                }
                if (temp == null || temp.size() == 0) {
                    mRecyclerView.stopRefresh(false);
                } else {
                    userBookBoList.addAll(temp);
                    StringBuilder actIds = new StringBuilder();
                    for (UserBookBo userBookBo : userBookBoList) {
                        actIds.append(userBookBo.getActId()).append(",");
                    }
                    actIds.deleteCharAt(actIds.length() - 1);
                    newEstActListApi.setActIds(actIds.toString());
                    newEstActListApi.startRequest();
                }
            }

            @Override
            public void onErrorResponse(VolleyError error) {
                mRecyclerView.refreshError();
            }
        });

        newEstActListApi = new NewEstActListApi(MyActivityActivity.class, NewEstActListRo.class, new IResponseListener<NewEstActListRo>() {
            @Override
            public void onResponse(NewEstActListRo newEstActListRo) {
                ArrayList<NewEstActDo> temp = newEstActListRo.getList();
                if (iRefreshType == 1) {
                    userActList.clear();
                }
                userActList.addAll(newEstActListRo.getList());
                mRecyclerView.stopRefresh(temp.size() == 10);
            }

            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });
        userInfo();
        newEstActListApi.setUsedActIds(1);
        newPropImg();
    }

    private void requestUserBookingList() {
        userBookingListApi.startRequest();
    }


    /**
     * 用户信息
     */
    private void userInfo() {
        RxDataBase.getUser()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(this.<UserDo>bindUntilEvent(ActivityEvent.DESTROY))
                .subscribe(new Action1<UserDo>() {
                    @Override
                    public void call(UserDo userDo) {
                        if (userDo != null)
                            userPhone = userDo.getPhone();
                        checkLogin();
                    }
                });
    }

    private void checkLogin() {
        if (AppConstant.IsLogin) {
            if (TextUtils.isEmpty(userPhone)) {
                startActivityForResult(new Intent(this, BindingPhoneActivity.class),
                        CommonConstant.REQ_BIND_MOBILE);
            } else {
                mRecyclerView.startRefresh();
            }
        } else {
            startActivityForResult(new Intent(MyActivityActivity.this, LoginActivity.class),
                    CommonConstant.REQ_LOGIN);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (RESULT_OK == resultCode) {
            switch (requestCode) {
                case CommonConstant.REQ_BIND_MOBILE:
                case CommonConstant.REQ_LOGIN:
                    userInfo();
                    break;
                default:
                    break;
            }
        } else {
            finish();
        }
    }

    private void newPropImg() {
        RxDataBase.getBizUnit()
                .compose(this.<BizUnitDo>bindUntilEvent(ActivityEvent.DESTROY))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<BizUnitDo>() {
                    @Override
                    public void call(BizUnitDo bizUnitDo) {
                        newEstActAdapter.setNewPropImg(bizUnitDo.getNewpropimg());
                    }
                });
    }
}